package lwlk.controller;

import lwlk.dao.UserDao;
import lwlk.model.User;
import lwlk.tools.PasswordHash;
import org.beetl.ext.spring.BeetlGroupUtilConfiguration;
import org.beetl.sql.core.SQLManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Objects;
import java.util.Optional;

@Controller
public class IndexController {

    @Autowired
    private SQLManager sqlManager;

    @Autowired
    private BeetlGroupUtilConfiguration configuration;

    @Autowired
    private UserDao userDao;

    @RequestMapping(value = "/addUser", method = RequestMethod.GET, produces = { "text/html; charset=UTF-8" })
    private @ResponseBody String addUser(User user) {

        if(userDao.selectSingleByAccount(user.getAccount()) != 0) return "false";

        userDao.insert(user.encodePassword());

        return "true";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    private ModelAndView login() {

        ModelAndView mv = new ModelAndView("/beetl/login");

        mv.addObject("redirectUrl", "ohoho");

        return mv;
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    private ModelAndView login(User user) {

        ModelAndView mv = new ModelAndView("/beetl/login");

        mv.addObject("redirectUrl", "ohoho - 2");

        if(Objects.isNull(user)) {

            mv.addObject("errorMessage", "未得到User数据");

            return mv;
        }

        do {

            Optional<User> maybeUser = Optional.ofNullable(userDao.selectByAccount(user.getAccount()));

            if(!maybeUser.isPresent()) {

                mv.addObject("errorMessage", "用户不存在");

                break;
            }

            if(!PasswordHash.validatePassword(user.getPassword(), maybeUser.get().getPassword())) {

                mv.addObject("errorMessage", "密码不正确");

                break;
            }

            mv.addObject("errorMessage", "登录成功");


        } while(false);

        return mv;
    }
}
